Ext.ns('OfficeInfoView');

OfficeInfoView = Ext.extend(Ext.Panel, {
	constructor : function(config) {
		Ext.applyIf(this, config);
		this.initUIComponents();
		OfficeInfoView.superclass.constructor.call(this, {
					id : 'OfficeInfoView',
					title : '物业管理处基本信息',
					iconCls : 'menu-appuser',
					autoScroll : true,
					layout:'border',
					items : [this.treePanel, this.gridPanel]
				});
	},
	initUIComponents : function() {
		var selected = {};
		
		var treePanel = new Ext.tree.TreePanel({
					region : 'west',
					id : 'dep_treePanel',
					title : '物业公司信息',
					collapsible : true,
					autoScroll : true,
					split : true,
					height : 800,
					width : 220,
					tbar : new Ext.Toolbar({
						items : [{
									xtype : 'button',
									iconCls : 'btn-refresh',
									text : '刷新',
									handler : function() {
										Ext.getCmp('officeAddBut').disable();
										treePanel.root.reload();
									}
								}, {
									xtype : 'button',
									text : '展开',
									iconCls : 'btn-expand',
									handler : function() {
										treePanel.expandAll();
									}
								}, {
									xtype : 'button',
									text : '收起',
									iconCls : 'btn-collapse',
									handler : function() {
										treePanel.collapseAll();
									}
								}]
					}),
					loader : new Ext.tree.TreeLoader({
								url : __ctxPath+ '/system/treeByLevelDepartment.do'
							}),
					root : new Ext.tree.AsyncTreeNode({
								expanded : true
							}),
					rootVisible : false,
					listeners : {
						'click' : function(node) {
							selected.id	  = node.id;
							selected.text = node.text;
							selected.code = node.attributes.code;
							if (node != null) {
								Ext.getCmp('officeAddBut').enable();	//officeAddBut enable
								var store = Ext.getCmp('OfficeInfoGrid').getStore();
								store.baseParams = {
									'department.depId' : node.id
								};
								store.reload({
											params : {
												start : 0,
												limit : 25
											}
										});
							}
						}
					}
				});
		this.treePanel = treePanel;				
		// 树的右键菜单的
		treePanel.on('contextmenu', contextmenu, treePanel);

		// 创建右键菜单
		var treeMenu = new Ext.menu.Menu({
					id : 'DepartmentTreeMenu',
					items : [{
								text : '新建子公司',
								iconCls : 'btn-add',
								handler : function(){
									newNodeForm(true);
								}
							}, {
								text : '修改子公司信息',
								iconCls : 'btn-edit',
								handler : function(){
									newNodeForm(false);
								}
							}, {
								text : '删除子公司',
								iconCls : 'btn-delete',
								handler : deteleNode
							}]
				});

		function contextmenu(node, e) {
			Ext.getCmp('dep_treePanel').fireEvent('click',node);	//触发click事件
			treeMenu.showAt(e.getXY());
		}

		function deteleNode() {
			var depId = selected.id;
			var myMask = new Ext.LoadMask(Ext.getBody(), {
				msg : '正在提交，请稍候！',
				removeMask : true
			});
			myMask.show();
			Ext.Ajax.request({
					url : __ctxPath
							+ '/system/delDepartment.do?department.depId='
							+ depId,
					success : function() {
						Ext.ux.Toast.msg("操作信息", "删除成功");
						myMask.hide();
						Ext.getCmp('officeAddBut').disable();
						Ext.getCmp('dep_treePanel').root.reload();
					},
					failure : function(response) {
						myMask.hide();
						var res = Ext.util.JSON.decode(response.responseText);
						Ext.Msg.alert("操作信息", "删除失败，" + res.msg);
					}
			});
		}

		function newNodeForm(add) {
			new Ext.Window({
				title : (add?'为<span style="color:#f00;">' + (selected.text) + '</span>新增子公司':'修改子公司'),
				id : 'CreateDepWin',
				width : 405,
				resizable : false,
				items : [{
					xtype : 'form',
					frame : true,
					border: false,
					width : 400,
					id : 'CreateDepForm',
					items : [{
						xtype : 'textfield',
						id : 'department_depCode',
						name  : 'department.depCode',
						allowBlank : false,
						fieldLabel : '子公司编号',
						width : 260,
						value : (add?'':selected.code),
						disabled : !add,
						listeners : {
							blur : function(){
								if(this.getValue()!=""){
									Ext.Ajax.request({
										url : __ctxPath+ '/system/listDepartment.do',
										params:{
											'Q_depCode_S_EQ': this.getValue(),
											'Q_parentId_L_EQ' : selected.id
										},
										success : function(response) {
											var d = eval("("+ response.responseText+ ")");
											if(d.result.length>0){
												Ext.Msg.alert('信息','该子公司编号已经存在.');
												Ext.getCmp('department_depCode').setValue('');
											}
										},
										failure : function(){
											Ext.Msg.alert('信息','验证编号失败.');
												Ext.getCmp('department_depCode').setValue('');
										}
									});
								}
							}
						}
					},{
						xtype : 'textfield',
						id : 'department_depName',
						name  : 'department.depName',
						fieldLabel : '子公司名称',
						allowBlank : false,
						value : (add?'':selected.text),
						dbValue :(add?'':selected.text),
						width : 260,
						listeners : {
							blur : function(){
								if(this.dbValue!=this.getValue()){
									Ext.Ajax.request({
										url : __ctxPath+ '/system/listDepartment.do',
										params:{
											'Q_depName_S_EQ': this.getValue(),
											'Q_parentId_L_EQ' : selected.id
										},
										success : function(response) {
											var d = eval("("+ response.responseText+ ")");
											if(d.result.length>0){
												Ext.Msg.alert('信息','该子公司名称已经存在.');
												Ext.getCmp('department_depName').setValue('');
											}
										},
										failure : function(){
											Ext.Msg.alert('信息','验证名称失败.');
												Ext.getCmp('department_depName').setValue('');
										}
									});
								} 
							}
						}
					}, {
						xtype : 'hidden',
						name  : add?'department.parentId':'department.depId',
						value : selected.id
					}]
				}],
				listeners : {
					'close' : function() {Ext.getBody().unmask();}
				},
				buttons : [{
					text : '保存',
					iconCls : 'btn-save',
					scope : this,
					handler : function() {
						var fp = Ext.getCmp('CreateDepForm');
						if (fp.getForm().isValid()) {
							fp.getForm().submit({
								scope : this,
								url : __ctxPath + '/system/saveDepartment.do',
								method : 'post',
								waitMsg : '正在提交数据...',
								success : function(fp, action) {
									Ext.ux.Toast.msg('操作信息', '信息保存成功！');
									Ext.getCmp('officeAddBut').disable();
									Ext.getCmp('dep_treePanel').root.reload();
									Ext.getCmp("CreateDepWin").close();
								},
								failure : function(fp, action) {
									Ext.MessageBox.show({
												title : '操作信息',
												msg : '信息保存失败!',
												buttons : Ext.MessageBox.OK,
												icon : 'ext-mb-error'
											});
								}
							});
						}
					}
				}, {
					text : '取消',
					iconCls : 'btn-cancel',
					scope : this,
					handler : function() {
						Ext.getCmp("CreateDepWin").close();
					}
				}]
			}).show();
		}

		function editNode() {
			var depId = selected.id;
			var departmentForm = Ext.getCmp('departmentForm');
			if (departmentForm == null) {
				new DepartmentForm().show();
				departmentForm = Ext.getCmp('departmentForm');
			}
			departmentForm.form.load({
				url : __ctxPath + '/system/getDepartment.do?depId='+depId,
				method : 'post',
				deferredRender : true,
				layoutOnTabChange : true,
				failure : function() {
					Ext.ux.Toast.msg('编辑', '载入失败');
				}
			});
		}
		
		
		//grid============
		this.toolbar = new Ext.Toolbar({
					height : 30,
					items : []
				});
		if (isGranted('_DepartmentAdd')) {
			this.toolbar.add(new Ext.Button({
						text : '新增',
						id:'officeAddBut',
						disabled:true,
						iconCls : 'add-user',
						handler : function() {
							new OfficeInfoForm({
								pid : selected.id
							}).show();
						}
					}));
		} else {
			this.toolbar = null;
		}

		var store = new Ext.data.JsonStore({
			url : __ctxPath + '/system/selectDepartment.do?Q_depLevel_N_EQ=2',//管理处
			root : 'result',
			totalProperty : 'totalCounts',
			fields : ['depId', 'depCode', 'depName', 'officeBoss',
					'officeAddress', 'officeTel', 'officeWorkingHours'],
			remoteSort : true
		});
		store.setDefaultSort('path', 'asc');
		
		var sm = new Ext.grid.CheckboxSelectionModel();
		var cm = new Ext.grid.ColumnModel({
			columns : [new Ext.grid.RowNumberer(), {
						header : "管理处编号",
						dataIndex : 'depCode',
						width : 100
					}, {
						header : "管理处名称",
						dataIndex : 'depName'
					}, {
						header : "管理处负责人",
						dataIndex : 'officeBoss',
						width : 100
					}, {
						header : "管理处地址",
						dataIndex : 'officeAddress',
						width : 160
					}, {
						header : "管理处电话",
						dataIndex : 'officeTel',
						width : 100
					}, {
						header : "工作时间",
						dataIndex : 'officeWorkingHours',
						width : 100
					}, {
						header : '操作',
						width : 80,
						dataIndex : 'depId',
						renderer : function(v) {
							var str = '';
							if (isGranted('_DepartmentDel')) {
								str += '<button title="删除" value=" " class="btn-del" onclick="OfficeInfoView.remove('
										+ v + ')"></button>';
							}
							if (isGranted('_DepartmentEdit')) {
								str += '&nbsp;<button title="编辑" value=" " class="btn-edit" onclick="OfficeInfoView.edit('
										+ v + ')"></button>';
							}

							return str;
						}
					}],
			defaults : {
				sortable : true,
				menuDisabled : true,
				width : 100
			}
		});

		this.gridPanel = new Ext.grid.GridPanel({
					region : 'center',
					id : 'OfficeInfoGrid',
					tbar : this.toolbar,
					store : store,
					autoHeight : true,
					shim : true,
					trackMouseOver : true,
					disableSelection : false,
					loadMask : true,
					cm : cm,
					sm : sm,
					viewConfig : {
						forceFit : true,
						enableRowBody : false,
						showPreview : false
					},
					bbar : new Ext.PagingToolbar({
								pageSize : 15,
								store : store,
								displayInfo : true,
								displayMsg : '当前显示从{0}至{1}， 共{2}条记录',
								emptyMsg : "当前没有记录"
							})
				});
	}
});

OfficeInfoView.remove = function(depId) {
	Ext.Msg.confirm('删除操作', '你确定要删除吗?', function(btn) {
		if (btn == 'yes') {
			Ext.Ajax.request({
				url : __ctxPath
						+ '/system/delDepartment.do?department.depId='
						+ depId,
				success : function() {
					Ext.ux.Toast.msg("操作信息", "删除成功");
					Ext.getCmp('OfficeInfoGrid').getStore()
							.reload();
				},
				failure : function(response) {
					var obj = eval("(" + response.responseText
							+ ")");
					Ext.Msg.alert("操作信息", "删除失败，" + obj.msg);
				}
			});
		}
	});
};

OfficeInfoView.edit = function(recId) {
	new OfficeInfoForm({
				recId : recId
			}).show();
}
